package com.wnxy.sdd.service.impl;
import com.google.common.collect.Lists;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wnxy.sdd.entity.Chapter;
import com.wnxy.sdd.entity.Video;
import com.wnxy.sdd.mapper.ChapterMapper;
import com.wnxy.sdd.mapper.VideoMapper;
import com.wnxy.sdd.model.vo.ChapterVo;
import com.wnxy.sdd.model.vo.VideoVo;
import com.wnxy.sdd.service.IChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author Jet
 * @since 2023-06-21
 */
@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements IChapterService {

    @Autowired
    private VideoMapper videoMapper;

    @Override
    public List<ChapterVo> findChapterAndVideo(String courseId) {
        // 根据课程id查询课程下章节列表:
        // SELECT id,title FROM sdd_chapter WHERE course_id='' ORDER BY sort ASC
        List<Chapter> chapterList = this.list(
                Wrappers.lambdaQuery(Chapter.class)
                        .select(Chapter::getId, Chapter::getTitle) // 查询的字段
                        .eq(Chapter::getCourseId, courseId)  // 查询条件
                        .orderByAsc(Chapter::getSort)        // 指定升序排序字段
        );

        ///////////// 优化：一次把课程下所有的视频都查出来，程序中判断是哪一个章节的视频；减少数据库查询次数  /////////////
        //-- 根据课程id，查询课程下所有的视频
        //SELECT * FROM sdd_video WHERE course_id='1671352765549195266'
        List<Video> videoList = videoMapper.selectList(
                Wrappers.lambdaQuery(Video.class).eq(Video::getCourseId, courseId));

        // List<Chapter> 转换为：List<ChapterVo>
        List<ChapterVo> chapterVoList = chapterList.stream().map(chapter -> {
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(chapter,chapterVo);

            ///////////// 优化：循环中没有再查询数据库  /////////////
            // 遍历List<Video>，过滤（filter），映射（map）每一个元素转换为VideoVo，收集（collect）
            List<VideoVo> videoVoList = videoList.stream()
                    // 过滤：判断是否是当前章节下的视频
                    .filter(video -> chapter.getId().equals(video.getChapterId()))
                    .map(video -> {
                        VideoVo videoVo = new VideoVo();
                        BeanUtils.copyProperties(video, videoVo);
                        return videoVo;
                    }).collect(Collectors.toList());
            // 封装章节对应的视频
            chapterVo.setVideos(videoVoList);

            return chapterVo;
        }).collect(Collectors.toList());

        return chapterVoList;
    }
}
